package com.jl15988.simpletools.appcore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jl15988.simpletools.appcore.dto.ReviewDTO;
import com.jl15988.simpletools.appcore.dto.ReviewRequestDTO;
import com.jl15988.simpletools.appcore.entity.App;
import com.jl15988.simpletools.appcore.entity.Review;
import com.jl15988.simpletools.appcore.mapper.AppMapper;
import com.jl15988.simpletools.appcore.mapper.ReviewMapper;
import com.jl15988.simpletools.appcore.service.ReviewService;
import com.jl15988.simpletools.common.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 评论服务实现类
 *
 * @author jl15988
 */
@Service
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements ReviewService {

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private AppMapper appMapper;

    @Override
    public IPage<ReviewDTO> getReviewPage(Long appId, Integer pageNum, Integer pageSize) {
        // 检查应用是否存在
        App app = appMapper.selectById(appId);
        if (app == null) {
            throw new BusinessException("应用不存在");
        }

        Page<Review> page = new Page<>(pageNum, pageSize);
        IPage<Review> reviewPage = reviewMapper.selectReviewPage(page, appId);
        
        // 转换为DTO
        return reviewPage.convert(this::convertToDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createReview(ReviewRequestDTO request, Long userId, String username) {
        // 检查应用是否存在
        App app = appMapper.selectById(request.getAppId());
        if (app == null) {
            throw new BusinessException("应用不存在");
        }

        // 检查用户是否已评论过该应用
        LambdaQueryWrapper<Review> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Review::getAppId, request.getAppId())
                .eq(Review::getUserId, userId);
        if (reviewMapper.selectCount(wrapper) > 0) {
            throw new BusinessException("您已经评论过该应用");
        }

        Review review = new Review();
        BeanUtils.copyProperties(request, review);
        review.setUserId(userId);
        review.setUsername(username);
        review.setCreatedAt(LocalDateTime.now());
        review.setUpdatedAt(LocalDateTime.now());

        reviewMapper.insert(review);
        return review.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReview(ReviewRequestDTO request, Long userId) {
        // 检查评论是否存在
        Review review = reviewMapper.selectById(request.getId());
        if (review == null) {
            throw new BusinessException("评论不存在");
        }

        // 检查是否是评论作者
        if (!review.getUserId().equals(userId)) {
            throw new BusinessException("只能修改自己的评论");
        }

        BeanUtils.copyProperties(request, review);
        review.setUpdatedAt(LocalDateTime.now());

        return reviewMapper.updateById(review) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteReview(Long id, Long userId) {
        // 检查评论是否存在
        Review review = reviewMapper.selectById(id);
        if (review == null) {
            throw new BusinessException("评论不存在");
        }

        // 检查是否是评论作者
        if (!review.getUserId().equals(userId)) {
            throw new BusinessException("只能删除自己的评论");
        }

        return reviewMapper.deleteById(id) > 0;
    }

    @Override
    public double getAverageRating(Long appId) {
        // 检查应用是否存在
        App app = appMapper.selectById(appId);
        if (app == null) {
            throw new BusinessException("应用不存在");
        }

        // 查询所有评分
        LambdaQueryWrapper<Review> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Review::getAppId, appId)
                .select(Review::getRating);
        List<Review> reviews = reviewMapper.selectList(wrapper);
        
        if (reviews.isEmpty()) {
            return 0.0;
        }
        
        // 计算平均分
        double sum = reviews.stream()
                .mapToInt(Review::getRating)
                .sum();
        return Math.round((sum / reviews.size()) * 10) / 10.0;
    }

    /**
     * 将实体转换为DTO
     *
     * @param review 评论实体
     * @return 评论DTO
     */
    private ReviewDTO convertToDTO(Review review) {
        ReviewDTO dto = new ReviewDTO();
        BeanUtils.copyProperties(review, dto);
        return dto;
    }
} 